const mysql = require('mysql2/promise')
// const mongoose = require('mongoose')

const dbConfig = {
  // host: 'localhost',
  // user: 'root',
  host: '39.98.67.198',
  user: 'new_user',
  port: 3306,
  password: '123456',
  database: 'digitalpresencedatacore',
}

let mysqlPool

const createPool = async () => {
  if (!mysqlPool) {
    mysqlPool = await mysql.createPool(dbConfig)
  }
  return mysqlPool
}
/**
 * 获取数据库连接池
 */
const getPool = async () => {
  if (!mysqlPool) {
    mysqlPool = await createPool()
  }
  return mysqlPool
}
/**
 * 开启事务
 */
const beginTransaction = async () => {
  const pool = await getPool()
  const connection = await pool.getConnection()
  await connection.beginTransaction()
  return connection
}
/**
 * 提交事务
 * @param {Object} connection - 数据库连接对象
 */
const commitTransaction = async (connection) => {
  try {
    await connection.commit()
  } finally {
    connection.release() // 释放连接
  }
}

/**
 * 回滚事务
 * @param {Object} connection - 数据库连接对象
 */
const rollbackTransaction = async (connection) => {
  try {
    await connection.rollback()
  } finally {
    connection.release() // 释放连接
  }
}
module.exports = {
  createPool,
  // mongoose,
  getPool,
  beginTransaction,
  commitTransaction,
  rollbackTransaction,
}

/*
// MongoDB 配置
// const mongoURI = 'mongodb://localhost:27017/resume_portfolio_mongo'
// mongoose.connect(mongoURI, {
//   useNewUrlParser: true,
//   useUnifiedTopology: true,
// })

// const db = mongoose.connection
// db.on('error', console.error.bind(console, 'MongoDB connection error:'))
// db.once('open', () => {
//   console.log('Connected to MongoDB')
// })
*/
